import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../../../common/values/images.dart';
import '../../../common/routers/names.dart';
import '../../../common/utils/age_calculator.dart';

import 'index.dart';
import 'widgets/index.dart';

class MyIndexPage extends GetView<MyIndexController> {
  const MyIndexPage({super.key});

  // 数字格式化函数 - 企业级格式化规则
  String formatNumber(int number) {
    if (number >= 100000) {
      // 超过10万：显示1位小数w
      double result = number / 10000.0;
      String formatted = result.toStringAsFixed(1);
      // 去掉末尾的.0
      if (formatted.endsWith('.0')) {
        formatted = formatted.substring(0, formatted.length - 2);
      }
      return '${formatted}w';
    } else if (number >= 10000) {
      // 1万-10万：显示2位小数w
      double result = number / 10000.0;
      String formatted = result.toStringAsFixed(2);
      // 去掉末尾多余的0
      formatted = formatted.replaceAll(RegExp(r'\.?0+$'), '');
      return '${formatted}w';
    } else if (number >= 1000) {
      // 1千-1万：加逗号分隔
      return number.toString().replaceAllMapped(
        RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
        (Match match) => '${match[1]},',
      );
    } else {
      return number.toString();
    }
  }

  @override
  Widget build(BuildContext context) {
    // 定义更深的红色
    final Color deeperRed = Color(0xFFB84040);

    return GetBuilder<MyIndexController>(
      init: MyIndexController(),
      id: "my_index",
      builder: (controller) {
        return Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            toolbarHeight: 0, // 不显示AppBar，但用它来设置状态栏样式
            backgroundColor: Colors.white,
            elevation: 0,
            systemOverlayStyle: SystemUiOverlayStyle(
              statusBarColor: Colors.white, // 状态栏背景为白色
              statusBarIconBrightness: Brightness.dark, // 状态栏图标为黑色
              statusBarBrightness: Brightness.light, // iOS设置
            ),
            leading: IconButton(
              icon: const Icon(
                Icons.arrow_back_ios,
                color: Colors.black87,
                size: 20,
              ),
              onPressed: () => Get.back(),
            ),
          ),
          body: Column(
            children: [
              // 顶部编辑按钮
              Container(
                color: Colors.white,
                padding: EdgeInsets.only(right: 12.0, top: 8.0, bottom: 0, left: 12.0),
                alignment: Alignment.centerRight,
                child: GestureDetector(
                  onTap: () {
                    // 显示底部弹出框
                    _showEditProfileBottomSheet(context);
                  },
                  child: Image.asset(
                    AssetsImages.bEditPng,
                    width: 32,
                    height: 32,
                  ),
                ),
              ),
              // 内容区域
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      // 个人信息区
                      Padding(
                        padding: const EdgeInsets.symmetric(
                          vertical: 14.0,
                        ), // 稍微增加间距
                        child: Column(
                          children: [
                            // 用户头像、姓名等信息区域 - 点击跳转到用户主页
                            GestureDetector(
                              onTap: () => Get.toNamed(RouteNames.myUserInfo),
                              child: Stack(
                                alignment: Alignment.topRight,
                                children: [
                                  Column(
                                    children: [
                                      // 头像显示成圆形，从UserService获取
                                      ClipRRect(
                                        borderRadius: BorderRadius.circular(40),
                                        child: Obx(() => Image.network(
                                          controller.userService.userAvatar.isNotEmpty 
                                              ? controller.userService.userAvatar
                                              : 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_11.webp', // 默认头像
                                          width: 80,
                                          height: 80,
                                          fit: BoxFit.cover,
                                          loadingBuilder: (context, child, loadingProgress) {
                                            if (loadingProgress == null) return child;
                                            // 显示加载进度
                                            return Container(
                                              width: 80,
                                              height: 80,
                                              decoration: BoxDecoration(
                                                color: Colors.grey[200],
                                                borderRadius: BorderRadius.circular(40),
                                              ),
                                              child: Center(
                                                child: CircularProgressIndicator(
                                                  strokeWidth: 2,
                                                  valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD46A6A)),
                                                  value: loadingProgress.expectedTotalBytes != null
                                                      ? loadingProgress.cumulativeBytesLoaded /
                                                          loadingProgress.expectedTotalBytes!
                                                      : null,
                                                ),
                                              ),
                                            );
                                          },
                                          errorBuilder: (context, error, stackTrace) {
                                            // 头像加载失败时显示默认头像
                                            return Container(
                                              width: 80,
                                              height: 80,
                                              decoration: BoxDecoration(
                                                color: Colors.grey[300],
                                                borderRadius: BorderRadius.circular(40),
                                              ),
                                              child: Icon(Icons.person, size: 40, color: Colors.grey[600]),
                                            );
                                          },
                                        )),
                                      ),
                              
                                      const SizedBox(height: 10), // 稍微增加间距
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Obx(() => Text(
                                            controller.userService.userName.isNotEmpty 
                                                ? controller.userService.userName 
                                                : '用户',
                                            style: TextStyle(
                                              fontSize: 18,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          )),
                                          const SizedBox(width: 6),
                                          Obx(() => Container(
                                                padding: const EdgeInsets.symmetric(
                                                  horizontal: 6,
                                                  vertical: 2,
                                                ),
                                                decoration: BoxDecoration(
                                                  color: deeperRed,
                                                  borderRadius: BorderRadius.circular(10),
                                                ),
                                                child: Text(
                                                  controller.getLevelNameFromPoints(controller.userService.userPoints),
                                                  style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 12,
                                                  ),
                                                ),
                                              ),
                                          ),
                                        ],
                                      ),
                                      const SizedBox(height: 5),
                                      Obx(() {
                                        // 🔥 修复：使用动态年龄计算，参考MyApplication2的实现
                                        final userGender = controller.userService.currentUser?.userGender ?? "未知";
                                        final userBirthday = controller.userService.currentUser?.userBirthday;
                                        final userAge = AgeCalculator.formatAge(userBirthday);
                                        final userSignature = controller.userService.userSignature;
                                        
                                        final displayText = userSignature.isNotEmpty 
                                            ? '👁️ | $userGender | $userAge $userSignature'
                                            : '👁️ | $userGender | $userAge 这个人很懒，什么都没留下';
                                            
                                        return Text(
                                          displayText,
                                          style: TextStyle(
                                            color: Colors.black54,
                                            fontSize: 12,
                                          ),
                                          textAlign: TextAlign.center,
                                        );
                                      }),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                            const SizedBox(height: 14), // 稍微增加间距
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                Column(
                                  children: [
                                    Obx(() => Text(
                                      formatNumber(controller.userService.currentUser?.userLikes ?? 0),
                                      style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 17,
                                      ),
                                    )),
                                    Text(
                                      '点赞',
                                      style: TextStyle(fontSize: 12),
                                    ),
                                  ],
                                ),
                                // 粉丝部分 - 点击跳转到聊天列表
                                // 📝 按照MyApplication2逻辑，显示的是好友数量而非真正的粉丝数
                                GestureDetector(
                                  onTap: () => Get.toNamed(RouteNames.messageMessageIndex),
                                  child: Column(
                                    children: [
                                      Obx(() => Text(
                                        formatNumber(controller.friendCount),
                                        style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: 17,
                                        ),
                                      )),
                                      Text(
                                        '粉丝',
                                        style: TextStyle(fontSize: 12),
                                      ),
                                    ],
                                  ),
                                ),
                                Column(
                                  children: [
                                    Obx(() => Text(
                                      formatNumber(controller.userService.userPoints),
                                      style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 17,
                                      ),
                                    )),
                                    Text(
                                      '积分',
                                      style: TextStyle(fontSize: 12),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                      // 菜单卡片区
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 14.0),
                        child: Container(
                          decoration: BoxDecoration(
                            color: deeperRed, // 更深的红色
                            borderRadius: BorderRadius.circular(14),
                          ),
                          child: Column(
                            children: [
                              Obx(() => _buildMenuItemWithNotification(
                                AssetsImages.userPng,
                                '活动申请用户管理',
                                deeperRed,
                                hasNotification: controller.hasActivityApplication, // 绑定活动申请通知状态
                                onTap: () {
                                  // 清除活动申请通知状态（参考MyApplication2的逻辑）
                                  controller.clearActivityApplicationNotification();
                                  // 跳转到活动申请用户管理页面
                                  Get.toNamed('/activity_application_management');
                                },
                              )),
                              _buildMenuItem(
                                AssetsImages.rechargePng,
                                '积分充值',
                                deeperRed,
                                onTap: () => Get.toNamed(RouteNames.myFunds),
                              ),
                              _buildMenuItem(
                                AssetsImages.levelPng,
                                '等级和积分制度规则',
                                deeperRed,
                                onTap: () => Get.toNamed(RouteNames.myLevel),
                              ),
                              _buildMenuItem(
                                AssetsImages.securityPng,
                                '账号安全',
                                deeperRed,
                                onTap: () => Get.toNamed(RouteNames.mySecurity),
                              ),
                              _buildMenuItem(
                                AssetsImages.supportPng,
                                '反馈与客服',
                                deeperRed,
                                onTap: () => Get.toNamed(RouteNames.mySupport),
                              ),
                              Obx(() {
                                // 获取实名认证状态
                                final realNameAuth = controller.userService.currentUser?.extraData?['realNameAuth'];
                                final isVerified = realNameAuth != null && realNameAuth['verified'] == true;
                                
                                print('🔍 实名认证状态检查: $realNameAuth');
                                print('✅ 是否已认证: $isVerified');
                                
                                return _buildMenuItemWithStatus(
                                  AssetsImages.idCardPng,
                                  '实名认证',
                                  deeperRed,
                                  isVerified: isVerified,
                                  verificationText: isVerified ? '已认证' : '未认证',
                                  onTap: () => Get.to(() => const VerificationPage()),
                                );
                              }),
                              _buildMenuItem(
                                AssetsImages.settingPng,
                                '设置',
                                deeperRed,
                                isLast: true,
                                onTap: () => Get.toNamed(RouteNames.mySetting),
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 22), // 稍微增加间距
                      // 退出登录按钮
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 20.0),
                        child: SizedBox(
                          width: double.infinity,
                          height: 42, // 稍微增加高度
                          child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.black87,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(
                                  21,
                                ), // 稍微增加圆角
                              ),
                            ),
                            onPressed: () {
                              // 显示退出登录确认对话框
                              _showLogoutConfirmationDialog(context);
                            },
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(
                                  '退出登录',
                                  style: TextStyle(
                                    fontSize: 15,
                                    color: Colors.white,
                                  ),
                                ), // 稍微增加字体大小
                                SizedBox(width: 6),
                                Image.asset(
                                  AssetsImages.loginoutPng,
                                  width: 17, // 稍微增加大小
                                  height: 17, // 稍微增加大小
                                  color: Colors.white,
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(height: 22), // 稍微增加间距
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 显示退出登录确认对话框
  void _showLogoutConfirmationDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 30, horizontal: 20),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '是否退出该账号。',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 30),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    // 取消按钮
                    Expanded(
                      child: SizedBox(
                        height: 44,
                        child: ElevatedButton(
                          onPressed: () {
                            Navigator.of(context).pop(); // 关闭对话框
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.grey[200],
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(22),
                            ),
                            elevation: 0,
                          ),
                          child: Text(
                            '取消',
                            style: TextStyle(
                              color: Colors.black87,
                              fontSize: 16,
                            ),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 15),
                    // 确定按钮
                    Expanded(
                      child: SizedBox(
                        height: 44,
                        child: ElevatedButton(
                          onPressed: () {
                            Navigator.of(context).pop(); // 关闭对话框
                            // 执行退出登录操作
                            controller.logout();
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Color(0xFFFAE05E), // 黄色确认按钮
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(22),
                            ),
                            elevation: 0,
                          ),
                          child: Text(
                            '确定',
                            style: TextStyle(
                              color: Colors.black87,
                              fontSize: 16,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 显示编辑个人信息的底部弹出框
  void _showEditProfileBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true, // 允许弹出框高度超过半屏
      backgroundColor: Colors.white, // 确保背景是纯白色
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (BuildContext context) {
        return Container(
          height: MediaQuery.of(context).size.height * 0.8, // 弹出框高度为屏幕高度的80%
          padding: EdgeInsets.fromLTRB(16, 12, 16, 16), // 减少内边距使布局更紧凑
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题
              Padding(
                padding: EdgeInsets.only(bottom: 12), // 减少底部内边距
                child: Center(
                  child: Text(
                    '编辑我的信息',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                ),
              ),

              // 滚动内容区域
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      // 头像
                      _buildEditableProfileItem(
                        title: '头像',
                        trailing: Obx(() => Stack(
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(32),
                              child: Image.network(
                                controller.userService.userAvatar.isNotEmpty 
                                    ? controller.userService.userAvatar
                                    : 'https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_11.webp', // 默认头像
                                width: 64,
                                height: 64,
                                fit: BoxFit.cover,
                                loadingBuilder: (context, child, loadingProgress) {
                                  if (loadingProgress == null) return child;
                                  // 显示加载进度
                                  return Container(
                                    width: 64,
                                    height: 64,
                                    decoration: BoxDecoration(
                                      color: Colors.grey[200],
                                      borderRadius: BorderRadius.circular(32),
                                    ),
                                    child: Center(
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2,
                                        valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD46A6A)),
                                        value: loadingProgress.expectedTotalBytes != null
                                            ? loadingProgress.cumulativeBytesLoaded /
                                                loadingProgress.expectedTotalBytes!
                                            : null,
                                      ),
                                    ),
                                  );
                                },
                                errorBuilder: (context, error, stackTrace) {
                                  // 头像加载失败时显示默认头像
                                  return Container(
                                    width: 64,
                                    height: 64,
                                    decoration: BoxDecoration(
                                      color: Colors.grey[300],
                                      borderRadius: BorderRadius.circular(32),
                                    ),
                                    child: Icon(Icons.person, size: 36, color: Colors.grey[600]),
                                  );
                                },
                              ),
                            ),
                            // 上传进度指示器
                            if (controller.isUploading)
                              Container(
                                width: 64,
                                height: 64,
                                decoration: BoxDecoration(
                                  color: Colors.black54,
                                  borderRadius: BorderRadius.circular(32),
                                ),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    SizedBox(
                                      width: 24,
                                      height: 24,
                                      child: CircularProgressIndicator(
                                        value: controller.uploadProgress,
                                        strokeWidth: 2,
                                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                      ),
                                    ),
                                    SizedBox(height: 4),
                                    Text(
                                      '${(controller.uploadProgress * 100).toInt()}%',
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 10,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                          ],
                        )),
                        verticalPadding: 12,
                        onTap: () => controller.pickAndUploadAvatar(),
                      ),

                      // 昵称
                      _buildEditableProfileItem(
                        title: '昵称',
                        trailing: Obx(() => Text(
                          controller.userService.userName.isNotEmpty 
                              ? controller.userService.userName 
                              : '未设置',
                          style: TextStyle(color: Colors.black54),
                        )),
                        verticalPadding: 12,
                        onTap: () => _showEditDialog(
                          context,
                          '编辑昵称',
                          controller.userService.userName,
                          (value) => controller.updateUserName(value),
                        ),
                      ),

                      // 性别
                      _buildEditableProfileItem(
                        title: '性别',
                        trailing: Obx(() => Text(
                          controller.userService.currentUser?.userGender ?? '未知',
                          style: TextStyle(color: Colors.black54),
                        )),
                        verticalPadding: 12,
                        onTap: () => _showGenderPicker(context),
                      ),

                      // 🔥 年龄：自动计算显示，不可编辑
                      _buildNonEditableProfileItem(
                        title: '年龄',
                        trailing: Obx(() {
                          final userBirthday = controller.userService.currentUser?.userBirthday;
                          final ageText = AgeCalculator.formatAge(userBirthday);
                          return Text(
                            ageText,
                            style: TextStyle(color: Colors.black54),
                          );
                        }),
                        verticalPadding: 12,
                      ),

                      // 生日
                      _buildEditableProfileItem(
                        title: '生日',
                        trailing: Obx(() => Text(
                          controller.userService.currentUser?.userBirthday ?? '未设置',
                          style: TextStyle(color: Colors.black54),
                        )),
                        verticalPadding: 12,
                        onTap: () => _showDatePicker(context),
                      ),

                      // 签名
                      _buildEditableProfileItem(
                        title: '签名',
                        trailing: Obx(() => Text(
                          controller.userService.userSignature.isNotEmpty 
                              ? controller.userService.userSignature 
                              : '这个人很懒，什么都没留下',
                          style: TextStyle(color: Colors.black54),
                        )),
                        verticalPadding: 12,
                        onTap: () => _showEditDialog(
                          context,
                          '编辑签名',
                          controller.userService.userSignature,
                          (value) => controller.updateUserSignature(value),
                          maxLines: 3,
                        ),
                      ),

                      // 常出没地
                      _buildEditableProfileItem(
                        title: '常出没地',
                        trailing: Obx(() => Text(
                          controller.userService.currentUser?.userFrequentPlaces ?? '未知',
                          style: TextStyle(color: Colors.black54),
                        )),
                        verticalPadding: 12,
                        onTap: () => _showEditDialog(
                          context,
                          '编辑常出没地',
                          controller.userService.currentUser?.userFrequentPlaces ?? '',
                          (value) => controller.updateUserFrequentPlaces(value),
                        ),
                      ),

                      // 爱好
                      _buildInterestsSection(context),

                      // 相册
                      _buildAlbumSection(),

                      // 底部额外空间
                      SizedBox(height: 20), // 增加完成按钮与内容的距离
                    ],
                  ),
                ),
              ),

              // 完成按钮
              Padding(
                padding: EdgeInsets.only(bottom: 10), // 增加与底部的距离
                child: SizedBox(
                  width: double.infinity,
                  height: 46, // 稍微调整按钮高度
                  child: ElevatedButton(
                    onPressed: () async {
                      // 🔥 修复：直接关闭弹出框，不强制更新爱好
                      Navigator.pop(context); // 关闭弹出框
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Color(0xFFD46A6A), // 红色按钮
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(23), // 保持圆角为高度一半
                      ),
                    ),
                    child: Text(
                      '完成',
                      style: TextStyle(fontSize: 16, color: Colors.white),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }



  // 构建爱好部分（🔥 修改：可选择状态，与MyApplication2保持一致）
  Widget _buildInterestsSection(BuildContext context) {
    return GetBuilder<MyIndexController>(
      id: "my_index",
      builder: (controller) {
        return Container(
          padding: EdgeInsets.symmetric(vertical: 12),
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(color: Colors.grey.withOpacity(0.2), width: 1),
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '爱好',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(height: 12),
              // 🔥 修改：可点击选择的爱好按钮（与MyApplication2保持一致）
              Obx(() => Row(
                children: ['吃', '喝', '玩', '乐', '购'].map((hobby) {
                  final isSelected = controller.selectedHobbies[hobby] ?? false;
                  
                  return Padding(
                    padding: const EdgeInsets.only(right: 10),
                    child: GestureDetector(
                      onTap: () {
                        // 🔄 点击切换选中状态
                        controller.toggleHobby(hobby);
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                        decoration: BoxDecoration(
                          // 🎨 根据选中状态动态改变颜色（与MyApplication2一致）
                          color: isSelected 
                              ? Color(0xFFD46A6A) // 选中：红色背景
                              : Colors.grey[300], // 未选中：灰色背景
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Text(
                          hobby,
                          style: TextStyle(
                            // 🎨 根据选中状态动态改变文字颜色（与MyApplication2一致）
                            color: isSelected
                                ? Colors.white // 选中：白色文字
                                : Colors.black87, // 未选中：黑色文字
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),
                  );
                }).toList(),
              )),
              

            ],
          ),
        );
      },
    );
  }

  // 构建相册部分
  Widget _buildAlbumSection() {
    return GetBuilder<MyIndexController>(
      id: "my_index",
      builder: (controller) {
        return Container(
          padding: EdgeInsets.symmetric(vertical: 12),
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(color: Colors.grey.withOpacity(0.2), width: 1),
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '相册',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  // 📝 显示图片数量 (最多4张)
                  Obx(() {
                    final userImgUrls = controller.userService.currentUser?.userImgUrls ?? [];
                    const maxImages = 4; // 改回4张限制
                    return Text(
                      '${userImgUrls.length}/$maxImages',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                        fontWeight: FontWeight.w500,
                      ),
                    );
                  }),
                ],
              ),
              SizedBox(height: 12),
              Obx(() {
                final userImgUrls = controller.userService.currentUser?.userImgUrls ?? [];
                print('🖼️ 用户相册图片URLs: $userImgUrls');
                
                // 📝 限制：最多4张图片
                const maxImages = 4; // 限制为4张图片
                final showAddButton = userImgUrls.length < maxImages;
                
                return GridView.builder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4,
                    crossAxisSpacing: 12,
                    mainAxisSpacing: 12,
                    childAspectRatio: 1.0,
                  ),
                  // 📝 itemCount：现有图片 + （未达到限制时显示"+"按钮）
                  itemCount: userImgUrls.length + (showAddButton ? 1 : 0),
                  itemBuilder: (context, index) {
                    // 📝 最后一个位置显示"+"按钮（仅在未达到限制时）
                    if (showAddButton && index == userImgUrls.length) {
                      return GestureDetector(
                        onTap: () => _showAddAlbumImageOptions(context, controller),
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(
                              color: Colors.grey[300]!,
                              width: 2,
                              style: BorderStyle.solid,
                            ),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.add,
                                size: 32,
                                color: Colors.grey[600],
                              ),
                              SizedBox(height: 4),
                              Obx(() {
                                final currentCount = controller.userService.currentUser?.userImgUrls?.length ?? 0;
                                const maxImages = 4; // 限制为4张图片
                                final remaining = maxImages - currentCount;
                                return Column(
                                  children: [
                                    Text(
                                      '添加照片',
                                      style: TextStyle(
                                        color: Colors.grey[600],
                                        fontSize: 10,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                    if (remaining > 0) ...[
                                      SizedBox(height: 2),
                                      Text(
                                        '还可添加${remaining}张',
                                        style: TextStyle(
                                          color: Colors.grey[500],
                                          fontSize: 8,
                                        ),
                                      ),
                                    ]
                                  ],
                                );
                              }),
                            ],
                          ),
                        ),
                      );
                    }
                    
                    // 显示现有相册图片
                    final imageUrl = userImgUrls[index];
                    return GestureDetector(
                      onLongPress: () => _showAlbumImageOptions(context, controller, index, imageUrl),
                      child: Stack(
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(8),
                            child: Image.network(
                              imageUrl,
                              width: double.infinity,
                              height: double.infinity,
                              fit: BoxFit.cover,
                              errorBuilder: (context, error, stackTrace) {
                                return Container(
                                  decoration: BoxDecoration(
                                    color: Colors.grey[300],
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Icon(Icons.broken_image, color: Colors.grey[600], size: 20),
                                      SizedBox(height: 4),
                                      Text(
                                        '加载失败',
                                        style: TextStyle(
                                          color: Colors.grey[600],
                                          fontSize: 8,
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              },
                              loadingBuilder: (context, child, loadingProgress) {
                                if (loadingProgress == null) return child;
                                return Container(
                                  decoration: BoxDecoration(
                                    color: Colors.grey[100],
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: Stack(
                                    children: [
                                      // 背景图标
                                      Center(
                                        child: Icon(
                                          Icons.image,
                                          color: Colors.grey[400],
                                          size: 24,
                                        ),
                                      ),
                                      // 加载进度
                                      Center(
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            SizedBox(height: 30),
                                            SizedBox(
                                              width: 20,
                                              height: 20,
                                              child: CircularProgressIndicator(
                                                strokeWidth: 2,
                                                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD46A6A)),
                                                value: loadingProgress.expectedTotalBytes != null
                                                    ? loadingProgress.cumulativeBytesLoaded /
                                                        loadingProgress.expectedTotalBytes!
                                                    : null,
                                              ),
                                            ),
                                            SizedBox(height: 4),
                                            if (loadingProgress.expectedTotalBytes != null)
                                              Text(
                                                '${((loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!) * 100).toInt()}%',
                                                style: TextStyle(
                                                  color: Colors.grey[600],
                                                  fontSize: 8,
                                                  fontWeight: FontWeight.w500,
                                                ),
                                              ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ),

                        ],
                      ),
                    );
                  },
                );
              }),
            ],
          ),
        );
      },
    );
  }
  
  /// 🔥 新增：显示添加相册图片选项（与MyApplication2保持一致）
  void _showAddAlbumImageOptions(BuildContext context, MyIndexController controller) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
          ),
          child: SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 顶部装饰
                Container(
                  margin: EdgeInsets.only(top: 12),
                  width: 40,
                  height: 4,
                  decoration: BoxDecoration(
                    color: Colors.grey[300],
                    borderRadius: BorderRadius.circular(2),
                  ),
                ),
                
                // 标题
                Padding(
                  padding: EdgeInsets.all(20),
                  child: Text(
                    '添加照片',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                
                // 操作按钮
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20),
                  child: Column(
                    children: [
                      // 拍照按钮
                      ListTile(
                        leading: Container(
                          padding: EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: Color(0xFFD46A6A).withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Icon(Icons.camera_alt, color: Color(0xFFD46A6A)),
                        ),
                        title: Text('拍照'),
                        subtitle: Text('使用相机拍摄照片'),
                        onTap: () {
                          Navigator.pop(context);
                          controller.pickAndUploadAlbumImageFromCamera();
                        },
                      ),
                      
                      // 从相册选择按钮
                      ListTile(
                        leading: Container(
                          padding: EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: Color(0xFFD46A6A).withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Icon(Icons.photo_library, color: Color(0xFFD46A6A)),
                        ),
                        title: Text('从相册选择'),
                        subtitle: Text('从手机相册中选择照片'),
                        onTap: () {
                          Navigator.pop(context);
                          controller.pickAndUploadAlbumImageFromGallery();
                        },
                      ),
                    ],
                  ),
                ),
                
                // 取消按钮
                Padding(
                  padding: EdgeInsets.all(20),
                  child: SizedBox(
                    width: double.infinity,
                    height: 48,
                    child: ElevatedButton(
                      onPressed: () => Navigator.pop(context),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.grey[200],
                        foregroundColor: Colors.black87,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 0,
                      ),
                      child: Text(
                        '取消',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
  
  /// 显示相册图片操作选项
  void _showAlbumImageOptions(BuildContext context, MyIndexController controller, int index, String imageUrl) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
          ),
          child: SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 顶部装饰
                Container(
                  margin: EdgeInsets.only(top: 12),
                  width: 40,
                  height: 4,
                  decoration: BoxDecoration(
                    color: Colors.grey[300],
                    borderRadius: BorderRadius.circular(2),
                  ),
                ),
                
                // 图片预览
                Container(
                  margin: EdgeInsets.all(20),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Image.network(
                      imageUrl,
                      width: 100,
                      height: 100,
                      fit: BoxFit.cover,
                      loadingBuilder: (context, child, loadingProgress) {
                        if (loadingProgress == null) return child;
                        return Container(
                          width: 100,
                          height: 100,
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD46A6A)),
                                value: loadingProgress.expectedTotalBytes != null
                                    ? loadingProgress.cumulativeBytesLoaded /
                                        loadingProgress.expectedTotalBytes!
                                    : null,
                              ),
                              SizedBox(height: 8),
                              Text(
                                '加载中...',
                                style: TextStyle(
                                  color: Colors.grey[600],
                                  fontSize: 12,
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          width: 100,
                          height: 100,
                          decoration: BoxDecoration(
                            color: Colors.grey[300],
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(Icons.broken_image, color: Colors.grey[600], size: 32),
                              SizedBox(height: 4),
                              Text(
                                '加载失败',
                                style: TextStyle(
                                  color: Colors.grey[600],
                                  fontSize: 10,
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ),
                
                // 操作按钮
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20),
                  child: Column(
                    children: [
                      // 替换按钮
                      ListTile(
                        leading: Container(
                          padding: EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: Color(0xFFD46A6A).withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Icon(Icons.swap_horiz, color: Color(0xFFD46A6A)),
                        ),
                        title: Text('替换图片'),
                        subtitle: Text('选择新图片替换当前图片'),
                        onTap: () {
                          Navigator.pop(context);
                          controller.replaceAlbumImage(index);
                        },
                      ),
                      
                      // 删除按钮
                      ListTile(
                        leading: Container(
                          padding: EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: Colors.red.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Icon(Icons.delete_outline, color: Colors.red),
                        ),
                        title: Text('删除图片'),
                        subtitle: Text('从相册中移除这张图片'),
                        onTap: () {
                          Navigator.pop(context);
                          controller.deleteAlbumImage(index);
                        },
                      ),
                    ],
                  ),
                ),
                
                // 取消按钮
                Padding(
                  padding: EdgeInsets.all(20),
                  child: SizedBox(
                    width: double.infinity,
                    height: 48,
                    child: ElevatedButton(
                      onPressed: () => Navigator.pop(context),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.grey[200],
                        foregroundColor: Colors.black87,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 0,
                      ),
                      child: Text(
                        '取消',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildMenuItem(
    String imagePath,
    String title,
    Color backgroundColor, {
    bool isLast = false,
    Function()? onTap,
  }) {
    return Column(
      children: [
        ListTile(
          dense: true,
          contentPadding: EdgeInsets.symmetric(
            horizontal: 14,
            vertical: 2,
          ), // 稍微增加垂直方向间距
          leading: Image.asset(
            imagePath,
            width: 22, // 稍微增加大小
            height: 22, // 稍微增加大小
            color: Colors.white,
          ),
          title: Text(
            title,
            style: TextStyle(color: Colors.white, fontSize: 14),
          ), // 稍微增加字体大小
          trailing: Icon(
            Icons.chevron_right,
            color: Colors.white,
            size: 20,
          ), // 稍微增加大小
          onTap: onTap,
        ),
        if (!isLast)
          Divider(height: 1, color: Colors.white24, indent: 14, endIndent: 14),
      ],
    );
  }

  Widget _buildMenuItemWithStatus(
    String imagePath,
    String title,
    Color backgroundColor, {
    bool isLast = false,
    bool isVerified = false,
    String? verificationText, // 新增参数，允许自定义认证文本
    Function()? onTap,
  }) {
    return Column(
      children: [
        ListTile(
          dense: true,
          contentPadding: EdgeInsets.symmetric(
            horizontal: 14,
            vertical: 2,
          ),
          leading: Image.asset(
            imagePath,
            width: 22,
            height: 22,
            color: Colors.white,
          ),
          title: Text(
            title,
            style: TextStyle(color: Colors.white, fontSize: 14),
          ),
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 显示认证状态文本
              if (verificationText != null && verificationText.isNotEmpty)
                Text(
                  verificationText,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                  ),
                ),
              // 如果没有自定义文本但有验证状态，显示默认文本
              if (verificationText == null && isVerified)
                Text(
                  '已认证',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                  ),
                ),
              // 如果有认证相关文本，添加间距
              if ((verificationText != null && verificationText.isNotEmpty) || 
                  (verificationText == null && isVerified)) 
                SizedBox(width: 8),
              Icon(
                Icons.chevron_right,
                color: Colors.white,
                size: 20,
              ),
            ],
          ),
          onTap: onTap,
        ),
        if (!isLast)
          Divider(height: 1, color: Colors.white24, indent: 14, endIndent: 14),
      ],
    );
  }

  /// 构建带通知小圆点的菜单项
  Widget _buildMenuItemWithNotification(
    String imagePath,
    String title,
    Color backgroundColor, {
    bool isLast = false,
    bool hasNotification = false,
    Function()? onTap,
  }) {
    return Column(
      children: [
        ListTile(
          dense: true,
          contentPadding: EdgeInsets.symmetric(
            horizontal: 14,
            vertical: 2,
          ),
          leading: Stack(
            children: [
              Image.asset(
                imagePath,
                width: 22,
                height: 22,
                color: Colors.white,
              ),
              if (hasNotification)
                Positioned(
                  right: 0,
                  top: 0,
                  child: Container(
                    width: 8,
                    height: 8,
                    decoration: BoxDecoration(
                      color: Colors.orange,
                      shape: BoxShape.circle,
                    ),
                  ),
                ),
            ],
          ),
          title: Text(
            title,
            style: TextStyle(color: Colors.white, fontSize: 14),
          ),
          trailing: Icon(
            Icons.keyboard_arrow_right,
            color: Colors.white70,
            size: 20,
          ),
          onTap: onTap,
        ),
        if (!isLast)
          Divider(height: 1, color: Colors.white24, indent: 14, endIndent: 14),
      ],
    );
  }

  // 构建可编辑的个人信息条目
  Widget _buildEditableProfileItem({
    required String title,
    Widget? trailing,
    double verticalPadding = 16,
    Function()? onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: verticalPadding),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(color: Colors.grey.withOpacity(0.2), width: 1),
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              title,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            Row(
              children: [
                if (trailing != null) trailing,
                Padding(
                  padding: EdgeInsets.only(left: 8),
                  child: Icon(
                    Icons.chevron_right,
                    color: Colors.grey,
                    size: 20,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 🔥 新增：构建不可编辑的个人信息条目（用于年龄等自动计算的字段）
  Widget _buildNonEditableProfileItem({
    required String title,
    Widget? trailing,
    double verticalPadding = 16,
  }) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: verticalPadding),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.grey.withOpacity(0.2), width: 1),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          if (trailing != null) trailing,
        ],
      ),
    );
  }

  // 显示编辑对话框
  void _showEditDialog(
    BuildContext context,
    String title,
    String currentValue,
    Function(String) onSave, {
    int maxLines = 1,
  }) {
    final TextEditingController textController = TextEditingController(text: currentValue);

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          child: Padding(
            padding: EdgeInsets.all(20),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 16),
                // 输入框
                TextField(
                  controller: textController,
                  maxLines: maxLines,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    hintText: '请输入$title',
                  ),
                ),
                SizedBox(height: 20),
                // 按钮行
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    // 取消按钮
                    TextButton(
                      onPressed: () => Navigator.of(context).pop(),
                      child: Text(
                        '取消',
                        style: TextStyle(color: Colors.grey),
                      ),
                    ),
                    SizedBox(width: 12),
                    // 保存按钮
                    ElevatedButton(
                      onPressed: () {
                        final newValue = textController.text.trim();
                        if (newValue.isNotEmpty) {
                          onSave(newValue);
                          Navigator.of(context).pop();
                        }
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Color(0xFFD46A6A),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      child: Text(
                        '保存',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 显示性别选择器
  void _showGenderPicker(BuildContext context) {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (BuildContext context) {
        return Container(
          padding: EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '选择性别',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(height: 20),
              // 性别选项
              ...[
                {'label': '男', 'value': '男'},
                {'label': '女', 'value': '女'},
                {'label': '未知', 'value': '未知'},
              ].map((option) => ListTile(
                title: Text(option['label']!),
                onTap: () {
                  controller.updateUserGender(option['value']!);
                  Navigator.of(context).pop();
                },
              )).toList(),
            ],
          ),
        );
      },
    );
  }

  // 🔥 删除年龄选择器：年龄通过生日自动计算，不可直接编辑

  // 显示日期选择器
  void _showDatePicker(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime.now(),
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: ColorScheme.light(
              primary: Color(0xFFD46A6A),
              onPrimary: Colors.white,
              onSurface: Colors.black,
            ),
          ),
          child: child!,
        );
      },
    );

    if (picked != null) {
      final formattedDate = '${picked.year}-${picked.month.toString().padLeft(2, '0')}-${picked.day.toString().padLeft(2, '0')}';
      controller.updateUserBirthday(formattedDate);
    }
  }




}
